package com.dcits.mvc.base;

import java.util.HashMap;
import java.util.Map;

import com.dcits.constant.ConstantReturnCode;
import com.dcits.dto.RenderJSONBean;
import com.dcits.mvc.common.validator.UserKeyValidator;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;

@Before(UserKeyValidator.class)
public abstract class BaseController extends Controller {
	
	protected Map<String, Object> returnMap;
	
	/**
	 * 成功返回json
	 * @param data 返回数据
	 * @param msg 描述
	 */
	public void renderSuccess(Object data, String msg) {
		RenderJSONBean renderBean = new RenderJSONBean();
		renderBean.setReturnCode(ConstantReturnCode.SUCCESS);;
		renderBean.setData(returnMap != null ? returnMap : data);
		renderBean.setMsg(msg == null ? "success" : msg);
		renderJson(renderBean);
	}
	
	/**
	 * 失败返回json
	 * @param returnCode 自定义错误状态码
	 * @param msg 描述
	 */
	public void renderError(int returnCode, String msg) {
		RenderJSONBean renderBean = new RenderJSONBean();
		renderBean.setReturnCode(returnCode);;
		renderBean.setData(null);
		renderBean.setMsg(msg == null ? "error" : msg);
		renderJson(renderBean);
	}
	
	public BaseController setData(String key, Object value) {
		if (returnMap == null) {
			returnMap = new HashMap<String, Object>();
		}
		returnMap.put(key, value);
		return this;
	}
	
	public Map<String, Object> getReturnMap() {
		return returnMap;
	} 

}
